package com.yanqu.road.server.manger.kowloon.battle;

import com.yanqu.road.entity.kowloon.common.Rect;
import com.yanqu.road.entity.kowloon.common.Vec2;

public class KowloonBattleFunc {

    /**
     * Test rect and rect
     * 测试矩形与矩形是否相交
     *
     * @param a - The first rect
     * @param b - The second rect
     */
    public static boolean rectRect(Rect a, Rect b) {
        double a_min_x = a.getX();
        double a_min_y = a.getY();
        double a_max_x = a.getX() + a.getWidth();
        double a_max_y = a.getY() + a.getHeight();

        double b_min_x = b.getX();
        double b_min_y = b.getY();
        double b_max_x = b.getX() + b.getWidth();
        double b_max_y = b.getY() + b.getHeight();

        return a_min_x < b_max_x &&
                a_max_x > b_min_x &&
                a_min_y < b_max_y &&
                a_max_y > b_min_y;
    }

    /**
     * Test line and rect
     * 测试线段与矩形是否相交
     *
     * @param a1 - The start point of the line
     * @param a2 - The end point of the line
     * @param b  - The rect
     */
    public static boolean lineRect(Vec2 a1, Vec2 a2, Rect b) {
        Vec2 r0 = new Vec2(b.getX(), b.getY());
        Vec2 r1 = new Vec2(b.getX(), b.getMaxY());
        Vec2 r2 = new Vec2(b.getMaxX(), b.getMaxY());
        Vec2 r3 = new Vec2(b.getMaxX(), b.getY());
        return lineLine(a1, a2, r0, r1) || lineLine(a1, a2, r1, r2) || lineLine(a1, a2, r2, r3) || lineLine(a1, a2, r3, r0);
    }

    /**
     * Test line and line
     * 测试线段与线段是否相交
     *
     * @param a1 - The start point of the first line
     * @param a2 - The end point of the first line
     * @param b1 - The start point of the second line
     * @param b2 - The end point of the second line
     */
    public static boolean lineLine(Vec2 a1, Vec2 a2, Vec2 b1, Vec2 b2) {
        double ua_t = (b2.getX() - b1.getX()) * (a1.getY() - b1.getY()) - (b2.getY() - b1.getY()) * (a1.getX() - b1.getX());
        double ub_t = (a2.getX() - a1.getX()) * (a1.getY() - b1.getY()) - (a2.getY() - a1.getY()) * (a1.getX() - b1.getX());
        double u_b = (b2.getY() - b1.getY()) * (a2.getX() - a1.getX()) - (b2.getX() - b1.getX()) * (a2.getY() - a1.getY());
        if (u_b != 0) {
            double ua = ua_t / u_b;
            double ub = ub_t / u_b;
            return 0 <= ua && ua <= 1 && 0 <= ub && ub <= 1;
        }
        return false;
    }


}
